package HOT;

/**
 * Author  zxy
 * Date  2023/8/3 10:30
 */
public class PrintOddEven {
    private static final Object lock = new Object();
    private static int count = 1;
    private static final int MAX_COUNT = 100;

    public static void main(String[] args) {
        Thread oddThread = new Thread(PrintOddEven::printOdd);
        Thread evenThread = new Thread(PrintOddEven::printEven);

        oddThread.start();
        evenThread.start();
    }

    public static void printOdd() {
        while (count <= MAX_COUNT) {
            synchronized (lock) {
                if (count % 2 != 0) {
                    System.out.println("Odd: " + count);
                    count++;
                    lock.notify();
                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void printEven() {
        while (count <= MAX_COUNT) {
            synchronized (lock) {
                if (count % 2 == 0) {
                    System.out.println("Even: " + count);
                    count++;
                    lock.notify();
                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

